package org.digitarts.rtms.spring.collectors.shell.jms;

import java.util.Map;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.Topic;

import org.digitarts.rtms.helpers.StringHelper;
import org.digitarts.rtms.spring.collectors.ICollector;
import org.digitarts.rtms.spring.collectors.agent.jms.JMSAgentConstants;
import org.digitarts.rtms.spring.collectors.shell.IRemoteShell;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

public class RemoteJMSShell implements IRemoteShell
{

	protected Topic			requestTopic	= null;
	protected JmsTemplate	jmsTemplate		= null;

	public void setJmsTemplate(JmsTemplate jmsTemplate)
	{
		this.jmsTemplate = jmsTemplate;
	}

	public void setRequestTopic(Topic requestTopic)
	{
		this.requestTopic = requestTopic;
	}

	public void close()
	{
		// TODO Auto-generated method stub

	}

	public void init() throws Exception
	{
		// TODO Auto-generated method stub

	}

	public String issueOSCommand(String command, Map<String, ?>... context) throws Exception
	{
		return issueOSCommand(command, 0, context);
	}

	public String issueOSCommand(final String command, long timeOut, final Map<String, ?>... context) throws Exception
	{
		jmsTemplate.send(requestTopic, new MessageCreator()
		{
			public Message createMessage(Session session) throws JMSException
			{
				Message sMessage = session.createTextMessage(command);
				if (context != null && context.length > 0 && context[0] != null)
				{
					String commandSetBeanName = (String) context[0].get(JMSAgentConstants.COMMAND_SET_BEAN_NAME);
					if (commandSetBeanName != null)
					{
						sMessage.setStringProperty(JMSAgentConstants.COMMAND_SET_BEAN_NAME, commandSetBeanName);
					}
				}

				implementContext(sMessage, context);
				System.out.println("JMSShell Sent Message:\n==============\n" + sMessage + "\n==============");
				return sMessage;
			}
		});
		return null;
	}

	protected void implementContext(Message message, Map<String, ?>... context) throws JMSException
	{
		if (context == null)
			return;
		if (context[0] == null)
			return;
		Map<String, ?> contextMap = context[0];
		if (contextMap.containsKey(ICollector.TRACING_NAMESPACE_KEY))
		{
			String[] tracingNameSpace = (String[]) contextMap.get(ICollector.TRACING_NAMESPACE_KEY);
			String propertyValue = StringHelper.flattenArray(JMSAgentConstants.TRACING_NAMESPACE_DELIM, (Object[]) tracingNameSpace);
			message.setStringProperty(JMSAgentConstants.TRACING_NAMESPACE, propertyValue);
		}
	}

}
